package com.vegetable.modules.service.finance.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vegetable.common.utils.R;
import com.vegetable.modules.entity.finance.CustomerCollectionAlert;
import com.vegetable.modules.entity.finance.po.CustomerCollectionAlertQueryPO;
import com.vegetable.modules.entity.finance.vo.CustomerCollectionAlertVO;
import com.vegetable.modules.mapper.finance.CustomerCollectionAlertMapper;
import com.vegetable.modules.service.finance.ICustomerCollectionAlertService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 客户回款预警设置 服务实现类
 * </p>
 *
 * @author vegetable
 * @since 2025-10-24
 */
@Slf4j
@Service
public class CustomerCollectionAlertServiceImpl extends ServiceImpl<CustomerCollectionAlertMapper, CustomerCollectionAlert> 
        implements ICustomerCollectionAlertService {

    @Override
    public IPage<CustomerCollectionAlertVO> queryPage(CustomerCollectionAlertQueryPO queryPO) {
        Page<CustomerCollectionAlertVO> page = new Page<>(queryPO.getPage(), queryPO.getLimit());
        
        // 将PO对象转换为Map参数
        Map<String, Object> params = new HashMap<>();
        params.put("customerId", queryPO.getCustomerId());
        params.put("customerName", queryPO.getCustomerName());
        params.put("isEnabled", queryPO.getIsEnabled());
        params.put("alertLevel", queryPO.getAlertLevel());
        params.put("regionId", queryPO.getRegionId());
        
        IPage<CustomerCollectionAlertVO> result = baseMapper.selectAlertPage(page, params);
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R saveAlert(CustomerCollectionAlert alert) {
        try {
            // 检查是否已存在该客户的预警设置
            CustomerCollectionAlert existAlert = baseMapper.selectByCustomerId(
                    alert.getCustomerId(), alert.getRegionId());
            
            if (existAlert != null) {
                return R.fail("该客户已存在回款预警设置，请勿重复添加");
            }

            // 默认值设置
            if (alert.getAlertDays() == null) {
                alert.setAlertDays(30);
            }
            if (alert.getIsEnabled() == null) {
                alert.setIsEnabled(1);
            }
            if (alert.getAlertLevel() == null) {
                alert.setAlertLevel(1);
            }
            if (alert.getRegionId() == null) {
                alert.setRegionId(0);
            }

            boolean result = this.save(alert);
            if (result) {
                log.info("保存客户回款预警设置成功，客户ID：{}，预警天数：{}", 
                        alert.getCustomerId(), alert.getAlertDays());
                return R.success("保存成功");
            } else {
                return R.fail("保存失败");
            }
        } catch (Exception e) {
            log.error("保存客户回款预警设置失败", e);
            return R.fail("保存失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R updateAlert(CustomerCollectionAlert alert) {
        try {
            if (alert.getId() == null) {
                return R.fail("预警设置ID不能为空");
            }

            CustomerCollectionAlert existAlert = this.getById(alert.getId());
            if (existAlert == null) {
                return R.fail("预警设置不存在");
            }

            boolean result = this.updateById(alert);
            if (result) {
                log.info("更新客户回款预警设置成功，ID：{}", alert.getId());
                return R.success("更新成功");
            } else {
                return R.fail("更新失败");
            }
        } catch (Exception e) {
            log.error("更新客户回款预警设置失败", e);
            return R.fail("更新失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R deleteAlert(Long id) {
        try {
            if (id == null) {
                return R.fail("预警设置ID不能为空");
            }

            CustomerCollectionAlert existAlert = this.getById(id);
            if (existAlert == null) {
                return R.fail("预警设置不存在");
            }

            boolean result = this.removeById(id);
            if (result) {
                log.info("删除客户回款预警设置成功，ID：{}", id);
                return R.success("删除成功");
            } else {
                return R.fail("删除失败");
            }
        } catch (Exception e) {
            log.error("删除客户回款预警设置失败", e);
            return R.fail("删除失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R toggleAlert(Long id, Integer isEnabled) {
        try {
            if (id == null) {
                return R.fail("预警设置ID不能为空");
            }
            if (isEnabled == null || (isEnabled != 0 && isEnabled != 1)) {
                return R.fail("启用状态值无效");
            }

            CustomerCollectionAlert existAlert = this.getById(id);
            if (existAlert == null) {
                return R.fail("预警设置不存在");
            }

            CustomerCollectionAlert updateAlert = new CustomerCollectionAlert();
            updateAlert.setId(id);
            updateAlert.setIsEnabled(isEnabled);

            boolean result = this.updateById(updateAlert);
            if (result) {
                log.info("{}客户回款预警成功，ID：{}", isEnabled == 1 ? "启用" : "禁用", id);
                return R.success(isEnabled == 1 ? "启用成功" : "禁用成功");
            } else {
                return R.fail("操作失败");
            }
        } catch (Exception e) {
            log.error("切换客户回款预警状态失败", e);
            return R.fail("操作失败：" + e.getMessage());
        }
    }

    @Override
    public CustomerCollectionAlert getByCustomerId(Long customerId, Integer regionId) {
        return baseMapper.selectByCustomerId(customerId, regionId);
    }
}
